package weibo.database;

import java.sql.*;
import java.util.*;
import weibo.database.ConnectionTools;
import weibo.model.ReplyMod;
import weibo.model.TweetMod;
import weibo.model.UserMod;

/*
 * 点赞_回复
 */
public class PraiseDB {
	private Connection conn = null;

	/*
	 * 获取连接
	 */
	public PraiseDB() {
		ConnectionTools db = new ConnectionTools();
		conn = db.getConn();
	}
	/*
	 * 点赞
	 * 推文ID，点赞的用户ID
	 */
	public boolean CreatePraise(int tweet_id,int user_id){
		String sql="INSERT into up_or_down (uod_type,uod_userid,uod_tweetid,uod_createdate)VALUES(1,?,?,NOW())";
		try {
			java.sql.PreparedStatement exec=conn.prepareStatement(sql);
			exec.setInt(1,user_id);
			exec.setInt(2, tweet_id);
			int result=exec.executeUpdate();
			if (result>1 || result==0){
				conn.close();
				return false;
			}
			conn.close();
			return true;
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return false;
		}
	}
	/*
	 * 创建推文回复
	 * 推文ID，回复的用户ID，回复文本
	 */
	public boolean CreateReply(int tweet_id,int user_id,String text){
		String sql="INSERT INTO reply (tweet_id,user_id,text,create_date) VALUES (?,?,?,NOW())";
		try {
			java.sql.PreparedStatement exec=conn.prepareStatement(sql);
			exec.setInt(1,tweet_id);
			exec.setInt(2, user_id);
			exec.setString(3, text);
			int result=exec.executeUpdate();
			if (result>1 || result==0){
				conn.close();
				return false;
			}
			conn.close();
			return true;
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return false;
		}
	}
	/*
	 * 查询该用户推文回复
	 * 推文ID,起始位置,回复数量
	 */
	public List<ReplyMod> QueryTweetReply(int tweet_id,int start,int len){
		List<ReplyMod> praise=new ArrayList<ReplyMod>();
		String sql="select reply.*,`user`.user_name FROM reply,user WHERE reply.tweet_id=? and reply.user_id=user.userid ORDER BY reply.tweet_id DESC LIMIT ?,?";
		try {
			java.sql.PreparedStatement exec=conn.prepareStatement(sql);
			exec.setInt(1,tweet_id);
			exec.setInt(2, start);
			exec.setInt(3,len);
			ResultSet res=exec.executeQuery();
			while(res.next()){
				praise.add(new ReplyMod(
						res.getInt("tweet_id"),
						res.getInt("user_id"),
						res.getString("user_name"),
						res.getString("text"),
						res.getString("create_date")
						));
			}
			conn.close();
			return praise;
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return praise;
		}
	}
	/*
	 * 查询该用户被赞数量
	 */
	public int QueryPraiseUserCount(int userid){
		String sql="select COUNT(*) as total FROM tweet,user,up_or_down WHERE tweet.tweet_id=up_or_down.uod_tweetid and user.userid=tweet.tweet_userid and user.userid=? ";
		try {
			java.sql.PreparedStatement exec=conn.prepareStatement(sql);
			exec.setInt(1,userid);
			ResultSet res=exec.executeQuery();
			res.next();
			return res.getInt("total");
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return -1;
		}
	}

}
